angular.module('wenews.controllers', []).controller('AppCtrl', function ($scope, $ionicModal, $http, $state) {
    // 先判断网络连接是否正常
    if (!isOnline) {
        $state.go("app.offline");
    }

    // 获取菜单
    $scope.list = {};
    $scope.getList = function () {
        var url = "menu.json";
        $http.get(url).success(function (data) {
            $scope.list = data;
        });
    };
    $scope.getList();

}).controller('ListCtrl', function ($scope, $stateParams, $http, $ionicLoading, $ionicModal, $sce) {
    $scope.id = $stateParams.id;
    $scope.title = $stateParams.title;

    $scope.list = [];
    $scope.page = 0;
    $scope.noData = false, $scope.first = true;

    $scope.loadData = function () {
        $ionicLoading.show({
            template: "Loading..."
        });

        var url = "http://weixin.sogou.com/pcindex/pc/" + $scope.id + "/";
        if ($scope.page == 0) {
            url += $scope.id;
        } else {
            url += $scope.page;
        }
        url += ".html";

        $http.get(url).success(function (data) {
            // 清洗数据
            data = data.replace(/onload=".+"/g, "");
            data = data.replace(/onerror=".+"/g, "");
            // 解析数据
            var ele = document.createElement("html");
            ele.innerHTML = data;
            var lis = ele.querySelectorAll("li");
            for (var i = 0; i < lis.length; ++i) {
                var li = lis[i];
                var item = {};
                item['href'] = li.querySelector('.wx-img-box>a').href;
                item['thumbnail'] = li.querySelector('.wx-img-box img').src;
                item['title'] = li.querySelector(".wx-news-info2>h4>a").innerText;
                item['content'] = li.querySelector(".wx-news-info2>a").innerText;

                $scope.list.push(item);
            }

            $ionicLoading.hide();
            $scope.$broadcast('scroll.refreshComplete');
            $scope.$broadcast('scroll.infiniteScrollComplete');
        }).error(function () {
            $ionicLoading.hide();
        });
    };

    $scope.doRefresh = function () {
        $scope.page = 0;
        $scope.loadData();
    }

    $scope.loadMore = function () {
        if ($scope.page == 14) {
            $scope.noData = true;
        } else {
            if (!$scope.first) {
                $scope.page += 1;
            } else {
                $scope.page = 0;
                $scope.first = false;
            }
            $scope.loadData();
        }
    };

    //$scope.loadData();

    $ionicModal.fromTemplateUrl('modal.html', {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function (modal) {
        $scope.modal = modal;
    });
    // 使用modal iframe 打开 url
    /** 2015年8月12日 iframe加载会遇到微信图片 Uncaught SecurityError: Blocked a frame with origin "http://mp.weixin.qq.com" from accessing a frame with origin
     *  的问题，改用 inapp browser
     */
    $scope.openUrl = function (item) {
        window.open(item.href, "_blank", "location=yes,closebuttoncaption='关闭'");
        /*
         $ionicLoading.show({
         template: "Loading..."
         });

         $scope.subTitle = item.title;
         $scope.url = $sce.trustAsResourceUrl(item.href);
         $scope.modal.show();
         */
    };

    window.iframeLoaded = function () {
        $ionicLoading.hide();
    };

}).controller('SettingCtrl', function ($scope, $cordovaToast, $cordovaAppVersion, $http, $ionicPopup) {
    $scope.version = "0.0.0";
    if (window.cordova) {
        $cordovaAppVersion.getVersionNumber().then(function (version) {
            $scope.version = version;
        });
    }

    $scope.checkUpdate = function () {
        var url = "http://www.cnionic.com/web/index.php?s=/app/version/update/name/wenews";
        $http.get(url).success(function (ret) {
            if (ret.status == 1) {
                if ($scope.version != ret.data.version) {
                    var confirmPopup = $ionicPopup.confirm({
                        title: '新版本出炉，是否要升级？',
                        template: ret.data.description, // 更新内容
                        cancelText: '取消',
                        okText: '确定'
                    });
                    var downloadUrl = ret.data.url;
                    confirmPopup.then(function (res) {
                        if (res) {
                            // todo 保存更新日期到本地 , 检查更新，每天一次
                            // 调用系统浏览器下载
                            window.open(downloadUrl, '_system', 'location=yes');
                        }
                    });
                } else {
                    $cordovaToast.showLongBottom('已经是最新版本了');
                }
            } else {
                $cordovaToast.showLongBottom(ret.info);
            }
        });
    };
}).controller('OfflineCtrl', function ($scope, $location) {
    $scope.refresh = function () {
        if (isOnline) {
            $location.path('/app/list/pc_9/科技咖');
        }
    }
});
